// @flow
import React, { Component, Fragment, type Node } from 'react';

import './TreeNode.scss';

type Props = {
    datas: Array<any>,
    openedIds: Array<string>,
    treeType: string,
    NodeRender(item: any, isLeaf: boolean, isOpen: boolean, nodeType: string): Node
    // leafIcon: Node,
    // openningIcon: Node,
    // closingIcon: Node
};

class TreeNode extends Component<Props> {
    // constructor(props: Props) {
    //     super(props);
    // }
    arrFilter = (level: number = 0, pid: string = '') => {
        return this.props.datas.filter(i => {
            return i.level === level && i.pid === pid;
        });
    };
    itemRender = (level: number = 0, pid: string = '') => {
        const nodeItems = this.arrFilter(level, pid).map((item, k) => {
            const childrenItem = this.arrFilter(level + 1, item.id);
            window.tree = [];
            window.tree.splice(0, 0, {
                isLeaf: childrenItem.length === 0,
                isOpen: this.props.openedIds.indexOf(item.id) !== -1
            });
            return (
                <div className="tree-items" key={k} treeType={this.props.treeType}>
                    <div className="tree-item" style={{ display: 'flex' }}>
                        {this.props.NodeRender(
                            item,
                            childrenItem.length === 0,
                            this.props.openedIds.indexOf(item.id) !== -1,
                            item.type
                        )}
                    </div>
                    {childrenItem.length > 0 && this.props.openedIds.indexOf(item.id) !== -1
                        ? this.itemRender(level + 1, item.id)
                        : null}
                </div>
            );
        });
        return <ul className="tree-node">{nodeItems}</ul>;
    };
    render() {
        return <Fragment>{this.itemRender()}</Fragment>;
    }
}

export default TreeNode;
